package com.we823.cms.common.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class RequestUtil {

	/**
	 * 在request中根据name查找值，默认返回null
	 * @param request
	 * @param columnName 参数名
	 * @return 
	 */
	public static String getValueByName(HttpServletRequest request,String columnName) {
		return request.getParameter(columnName);
	}
	/**
	 * 在request中根据name查找值,如找不到就返回默认值
	 * @param request
	 * @param columnName
	 * @param defaultValue
	 * @return
	 */
	public static Integer getValueByName(HttpServletRequest request,String columnName,Integer defaultValue) {
		Integer iValue = defaultValue;
		String sValue = request.getParameter(columnName);
		if(sValue!=null){
			if(StringUtils.isNumeric(sValue)){
				iValue=Integer.parseInt(sValue);
			}
		}
		return iValue;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getValueByName(HttpServletRequest request,String columnName, T defaultValue){
		T dValue = defaultValue;
		String sValue = request.getParameter(columnName);
		if(defaultValue instanceof String){
			if(sValue!=null){
				return (T) sValue;
			}else{
				return defaultValue;
			}
		}else if(defaultValue instanceof Integer){
			Integer iValue = -1;
			if(sValue!=null){
				if(StringUtils.isNumeric(sValue)){
					iValue=Integer.parseInt(sValue);
				}
			}
			return (T) iValue;
		}
		return dValue;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getValueByName(HttpServletRequest request,String columnName, Class<T> classname){
		String sValue = request.getParameter(columnName);
		if(classname.equals(String.class)){
			if(sValue!=null){
				return (T) sValue;
			}else{
				return null;
			}
		}else if(classname.equals(Integer.class)){
			Integer iValue = -1;
			if(sValue!=null){
				if(StringUtils.isNumeric(sValue)){
					iValue=Integer.parseInt(sValue);
				}
			}
			return (T) iValue;
		}
		return null;
	}
	
	public static boolean getPageable(HttpServletRequest request) {
		String pageableString = RequestUtil.getValueByName(request, "pageable", "true");
        return !"false".equals(pageableString);
    }
	
	public static String[] getValuesByName(HttpServletRequest request,String name){
		String[] values = request.getParameterValues(name);
		if(values==null){
			values = new String[]{};
		}
		return values;
	}

    public static String getIp4(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
